package com.mm.ai.utils;

import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.command.CreateContainerResponse;
import com.github.dockerjava.api.command.InspectContainerResponse;
import com.github.dockerjava.api.model.Container;
import com.mm.ai.common.CommonException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @Author： tzy
 * @Date： 2024/11/13 22:25
 */
@Component
public class DockerUtil {
    @Autowired
    private DockerClient dockerClient;
    @Autowired
    private RestTemplate restTemplate;
    public static final String IMAGE_NAME = "zhayujie/chatgpt-on-wechat";
    public static final String CONTAINER_NAME = "tongxinhui2";
    public static final String TONGXINHUI_NETWORK = "my_tongxinhui_network";//服务器docker里必须先有这个网络


/*    public static final String IMAGE_NAME = "tomcat:9.0";
    public static final String CONTAINER_NAME = "tomcat";*/


    private static final String URL = "https://login.weixin.qq.com/jslogin";
    private static final String APPID = "wxb4baa461e1c3b1e9";
    private static final String FUN = "new";
    private static final String LANG = "zh_CN";

    public void startContainer(String containerName) {
        try {
            boolean containerStarted = checkAndStartContainer(CONTAINER_NAME);
            if (containerStarted) {
//                generateQrCode();
            } else {
                System.err.println("Failed to start the container.");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
//            stopContainer(CONTAINER_NAME);
            try {
                dockerClient.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }


    public boolean checkAndStartContainer(String containerName) {
        boolean r = false;
        r = isContainerExist(containerName);
        if (!r) {
            CreateContainerResponse container = dockerClient.createContainerCmd(IMAGE_NAME)
                    .withName(containerName)
                    .exec();

            dockerClient.startContainerCmd(container.getId()).exec();
        }

        // 检查容器是否启动成功
        try {
            InspectContainerResponse inspectResponse = dockerClient.inspectContainerCmd(containerName).exec();
            r = inspectResponse.getState().getRunning();
            if (r) {
                System.out.println("Container started: " + containerName);
            } else {
                System.err.println("Container did not start successfully.");
            }
        } catch (Exception e) {
            System.out.println("inspectContainerCmd error: " + containerName);
            try {
                dockerClient.startContainerCmd(containerName).exec();
                r = true;
            } catch (Exception ex) {
                r = false;
            }
        }
        return r;
    }

    public void stopContainer(String containerName) {
        try {
            dockerClient.stopContainerCmd(containerName).exec();
            dockerClient.removeContainerCmd(containerName).exec();
            System.out.println("Container stopped and removed.");
        } catch (Exception e) {
            System.err.println("Error stopping or removing container: " + e.getMessage());
        }
    }

    public boolean isContainerExist(String containerNameOrId) {
        try {
            List<Container> containerList = dockerClient.listContainersCmd().withShowAll(true).exec();
            for (Container container : containerList) {
                if (container.getId().equals(containerNameOrId) || Arrays.asList(container.getNames()).contains("/" + containerNameOrId)) {
                    return true;
                }
            }
        } catch (Exception e) {
            System.err.println("Error checking container existence: " + e.getMessage());
        }
        return false;
    }

    public void generateQrCode() {
        String uuid = getUuid();
        QrCodeGeneratorUtil.generateQrCode(uuid);
    }

    public String getUuid() {

        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers.set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3");

        // 构建请求参数
        String params = "appid=" + APPID +
                "&fun=" + FUN +
                "&lang=" + LANG +
                "&_=" + System.currentTimeMillis();

        HttpEntity<String> entity = new HttpEntity<>(headers);

        ResponseEntity<String> response = restTemplate.exchange(
                URL + "?" + params,
                HttpMethod.GET,
                entity,
                String.class
        );

        if (response.getStatusCode().is2xxSuccessful()) {
            String responseBody = response.getBody();
            System.out.println("Response Body: " + responseBody); // 打印响应体，方便调试
            Pattern pattern = Pattern.compile("window\\.QRLogin\\.code = (\\d+); window\\.QRLogin\\.uuid = \"(\\S+?)\"");
            Matcher matcher = pattern.matcher(responseBody);
            if (matcher.find()) {
                String code = matcher.group(1);
                String uuid = matcher.group(2);
                if ("200".equals(code)) {
                    return uuid;  // 返回uuid
                } else {
                    throw new CommonException("Failed to get QR code UUID: Code = " + code);
                }
            } else {
                throw new CommonException("Failed to parse UUID from response: " + responseBody);
            }
        } else {
            throw new CommonException("Request failed with status code: " + response.getStatusCodeValue());
        }
    }
}
